//4：假设有个Socket服务器，提供查询气温，风力，pm2.5,湿度等气象服务
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class WeatherServer {
    private static Executor severthread = Executors.newFixedThreadPool(30);

    public static void main(String[] args) {
        try {
            ServerSocket readSocket = new ServerSocket(9999);
            System.out.println("服务器已经启动");
            while (true) {
                Socket socket = readSocket.accept();
                weather(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void weather(Socket socket) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date time = new Date();
        Map<String, String> weatherMap = new HashMap<>();
        weatherMap.put("气温", "气温比较高");
        weatherMap.put("风力", "风力比较高");
        weatherMap.put("pm2.5", "pm2.5比较高");
        weatherMap.put("湿度", "湿度比较高");
        weatherMap.put("exit", "exit");
        severthread.execute(new Runnable() {
            @Override
            public void run() {
                String ip = socket.getInetAddress().getHostAddress();
                int socketPort = socket.getPort();
                InputStream input = null;
                OutputStream output = null;
                BufferedReader bf = null;
                PrintWriter pw = null;
                try {
                    input = socket.getInputStream();
                    output = socket.getOutputStream();
                    bf = new BufferedReader(new InputStreamReader(input));
                    pw = new PrintWriter(output, true);
                    while (true) {
                        String str = bf.readLine();
                        String s = weatherMap.keySet().stream().filter(e -> e.contains(str)).findFirst().orElse(null);
                        if (s == null) {
                            pw.println("没有你要的信息");
                        } else {
                            pw.println(weatherMap.get(s));
                        }
                        pw.println(format.format(time));
                        pw.println("0");
                    }
                } catch (Exception e) {
                    System.out.println("对方已经断开链接");
                } finally {
                    try {
                        input.close();
                        output.close();
                        bf.close();
                        pw.close();
                        socket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
    }
}